package com.wyzz.hr.bo.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.criterion.*;

import com.wyzz.hr.bo.UserBo;
import com.wyzz.hr.dao.UserDao;
import com.wyzz.hr.pojo.Authority;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Role;
import com.wyzz.hr.pojo.Userinfo;
import com.wyzz.hr.util.DatabaseSysConfigManager;
import com.wyzz.hr.util.MyTools;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.StringUtil;
import com.wyzz.hr.util.SysConfigManager;

public class UserBoImpl implements UserBo {

	public UserBoImpl() {
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public boolean delUser(String userId) {
		if (userId == null || userId.equals(""))
			return false;
		Userinfo u = (Userinfo) userDao.loadObject(Userinfo.class, userId,
				null, new boolean[0]);
		if (u != null) {
			userDao.deleteObject(u);
			return true;
		} else {
			return false;
		}
	}

	public List listUser() {
		String fetch[] = { "employee" };
		return userDao.getObjects(Userinfo.class, fetch);
	}

	public boolean addUser(Userinfo user, Integer roleNo[], String createrId) {
		if (user == null || roleNo == null)
			return false;
		user.setUiStatus(Integer.valueOf(1));
		Date date = new Date();
		user.setUiCreateTime(date);
		user.setUiLastChangeTime(date);
		if (createrId != null) {
			user.setUiCreateBy(new Employee(createrId));
			user.setUiLastChangeBy(new Employee(createrId));
		}
		String roleSets = MyTools.arrayToStr(roleNo, ',');
		System.out.println(roleSets);
		user.setUiRole(roleSets);
		String newAuths = getAuthoritysByRole(roleSets);
		System.out.println(newAuths);
		user.setUiAuth(newAuths);
		user.setUiIsGmHrCalc(newAuths);
		try {
			userDao.saveObject(user);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public List getEmpNoByDepAuth(String depNo, String authString) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteria
				.add(Restrictions
						.sqlRestriction((new StringBuilder())
								.append(
										"ui_emp_no in (select emp_no from employee  where emp_dept_no ='")
								.append(depNo).append("')").toString()));
		String auths[] = authString.split("or");
		ArrayList list = new ArrayList();
		Set authSet = new HashSet();
		int authsLength = auths.length;
		for (int i = 0; i < authsLength; i++)
			list.add(auths[i].split(","));

		String module = "";
		String condition = "";
		int listSize = list.size();
		for (int i = 0; i < listSize; i++) {
			String con[] = (String[]) list.get(i);
			module = null;
			condition = null;
			if (con.length > 1) {
				module = con[0].trim();
				condition = con[1].trim();
				if (condition != null && module != null) {
					DetachedCriteria temp = DetachedCriteria
							.forClass(com.wyzz.hr.pojo.Authority.class);
					temp.add(Restrictions.and(Restrictions.eq(
							"authorityModuleNo", module), Restrictions.eq(
							"authorityConditionNo", Integer.valueOf(Integer
									.parseInt(condition)))));
					authSet.addAll(userDao.findByCriteria(temp));
				}
				continue;
			}
			if (con.length != 1)
				continue;
			module = con[0];
			if (module != null) {
				DetachedCriteria temp = DetachedCriteria
						.forClass(com.wyzz.hr.pojo.Authority.class);
				temp.add(Restrictions.eq("authorityModuleNo", module));
				authSet.addAll(userDao.findByCriteria(temp));
			}
		}

		List userinfoList = userDao.findByCriteria(detachedCriteria);
		List empNoList = new ArrayList();
		Set empNoSet = new HashSet();
		int userinfoSize = userinfoList.size();
		label0: for (int i = 0; i < userinfoSize; i++) {
			Userinfo userInfo = (Userinfo) userinfoList.get(i);
			List userAuthList = userInfo.getUiAuthList();
			Iterator itor = authSet.iterator();
			Authority auth;
			do {
				if (!itor.hasNext())
					continue label0;
				auth = (Authority) itor.next();
			} while (!userAuthList.contains(auth.getId().toString()));
			empNoSet.add(userInfo.getId());
		}

		empNoList.addAll(empNoSet);
		return empNoList;
	}

	public List getEmpNoByAuth(String authString) {
		if (authString == null)
			return null;
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteria.add(Restrictions.like(Userinfo.PROP_UI_IS_GM_HR,
				(new StringBuilder()).append("%").append(authString.trim())
						.append("%").toString()));
		List list = userDao.findByCriteria(detachedCriteria);
		List result = new ArrayList();
		Userinfo userinfo;
		for (Iterator i$ = list.iterator(); i$.hasNext(); result.add(userinfo
				.getId()))
			userinfo = (Userinfo) i$.next();

		return result;
	}

	public List getEmpByAuth(String flowType) {
		String authString = null;
		if (flowType.equals("leaverequest")
				|| flowType.equals("overtimerequest"))
			authString = "H4";
		else if (flowType.equals("trainrequest"))
			authString = "H3";
		else if (flowType.equals("recruitrequest"))
			authString = "H6";
		if (authString == null) {
			return null;
		} else {
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Userinfo.class);
			detachedCriteria.setFetchMode("employee", FetchMode.JOIN);
			detachedCriteria.add(Restrictions.like(Userinfo.PROP_UI_IS_GM_HR,
					(new StringBuilder()).append("%").append(authString)
							.append("%").toString()));
			detachedCriteria.add(Restrictions.eq(Userinfo.PROP_UI_STATUS,
					new Integer(1)));
			List list = userDao.findByCriteria(detachedCriteria);
			return list;
		}
	}

	public List getUserinfoByAuth(String authString) {
		if (authString == null) {
			return null;
		} else {
			DetachedCriteria dc = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Userinfo.class);
			dc.createAlias("employee", "employee", 1);
			dc.createAlias((new StringBuilder()).append("employee.").append(
					Employee.PROP_EMP_DEPT_NO).toString(), "empDeptNo", 1);
			dc.createAlias((new StringBuilder()).append("employee.").append(
					Employee.PROP_EMP_PB_NO).toString(), "empPbNo", 1);
			dc.add(Restrictions.like(Userinfo.PROP_UI_IS_GM_HR,
					(new StringBuilder()).append("%").append(authString.trim())
							.append("%").toString()));
			dc.add(Restrictions.eq(Userinfo.PROP_UI_STATUS, new Integer(1)));
			List list = userDao.findByCriteria(dc);
			return list;
		}
	}

	public List searchAuthByEmpNo(String empNo) {
		DetachedCriteria detachedCriteriaA = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteriaA.add(Restrictions.eq(Userinfo.PROP_ID, empNo.trim()));
		List result = userDao.findByCriteria(detachedCriteriaA);
		if (result.size() != 1)
			return null;
		Userinfo userinfo = (Userinfo) result.get(0);
		List authList = userinfo.getUiAuthList();
		if (authList == null) {
			return null;
		} else {
			DetachedCriteria detachedCriteriaB = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Authority.class);
			detachedCriteriaB.add(Restrictions.in(Authority.PROP_ID, authList));
			return userDao.findByCriteria(detachedCriteriaB);
		}
	}

	public boolean existUserByName(String userName) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteria.add(Restrictions.eq(Userinfo.PROP_UI_USERNAME,
				userName));
		List list = userDao.findByCriteria(detachedCriteria);
		return list != null && list.size() == 1;
	}

	public Userinfo getUserByName(String userName) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteria.add(Restrictions.eq(Userinfo.PROP_UI_USERNAME,
				userName));
		List list = userDao.findByCriteria(detachedCriteria);
		if (list == null || list.size() < 1)
			return null;
		else
			return (Userinfo) list.get(0);
	}

	public Userinfo getUserById(String userId) {
		String fetch[] = new String[0];
		return (Userinfo) userDao.loadObject(com.wyzz.hr.pojo.Userinfo.class,
				userId, fetch, new boolean[0]);
	}

	public List getUserByIds(String ids[]) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteria.add(Restrictions.in(Userinfo.PROP_ID, ids));
		return userDao.findByCriteria(detachedCriteria);
	}

	public String updateUser(Userinfo user, Integer roleNo[], String createrId) {
		Userinfo oldUser = getUserById(user.getId());
		if (!oldUser.getUiUsername().equals(user.getUiUsername())
				&& existUserByName(user.getUiUsername()))
			return "\u5DF2\u5B58\u5728\u8BE5\u7528\u6237\u540D!";
		oldUser.setUiUsername(user.getUiUsername());
		oldUser.setUiStatus(user.getUiStatus());
		if (user.getUiStatus() == null)
			oldUser.setUiStatus(Integer.valueOf(1));
		if (createrId != null)
			oldUser.setUiLastChangeBy(new Employee(createrId));
		oldUser.setUiLastChangeTime(new Date());
		oldUser.setUiRoleEncrypt(MyTools.arrayToStr(roleNo, ','));
		String newAuths = getAuthoritysByRole(MyTools.arrayToStr(roleNo, ','));
		oldUser.setUiAuthEncrypt(newAuths);
		oldUser.setUiIsGmHrCalc(newAuths);
		userDao.updateObject(oldUser);
		return "yes";
	}

	public String updateUserAuth(Userinfo user, String auth) {
		try {
			user.setUiAuthEncrypt(auth);
			user.setUiIsGmHrCalc(auth);
			userDao.updateObject(user);
			return "yes";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "no";
	}

	public String doLogin(Userinfo user, String password, String macAddress) {
		Userinfo loginUser = getUserByName(user.getUiUsername());
		if (loginUser == null)
			return "\u65E0\u6B64\u7528\u6237\uFF01";// 无此用户！
		user.setId(loginUser.getId());
		// user.setUiPasswordEncrypt(StringUtil.encodePassword(password));
		user.setUiPassword(password);
		if (loginUser.getUiPassword().trim().compareTo(
				user.getUiPassword().trim()) != 0) {
			System.out.println(user.getUiPasswordDecrypt().trim()
					+ "===========" + loginUser.getUiPasswordDecrypt().trim());
			return "\u5BC6\u7801\u9519\u8BEF\uFF01";// 密码错误！
		}
		if (loginUser.getUiStatus().intValue() == 0)
			return "\u7528\u6237\u5DF2\u88AB\u505C\u7528\uFF01";// 用户已被停用！
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.add(Restrictions.eq("id", loginUser.getId()));
		List list = userDao.findByCriteria(detachedCriteria);
		if (((Employee) list.get(0)).getEmpStatus().intValue() == 0)
			return "\u79BB\u804C\u5458\u5DE5\u4E0D\u80FD\u767B\u5F55\uFF01";// 离职员工不能登录
		// ！
		HttpServletRequest request;
		if (ServletActionContext.getRequest() != null)
			request = ServletActionContext.getRequest();
		else
			request = WebContextFactory.get().getHttpServletRequest();
		String loginIp = request.getRemoteAddr();
		user.setUiLastLoginIp(loginIp);

		Date date = loginUser.getUiCurrentLoginTime();
		if (date != null)
			loginUser.setUiLastLoginTime(date);
		else
			loginUser.setUiLastLoginTime(new Date());
		loginUser.setUiCurrentLoginTime(new Date());
		loginUser.setUiLastLoginIp(user.getUiLastLoginIp());
		userDao.updateObject(loginUser);
		return "yes";
	}

	public boolean updatePassword(String userId, String password2) {
		Userinfo user = (Userinfo) userDao.loadObject(
				com.wyzz.hr.pojo.Userinfo.class, userId, null, new boolean[0]);
		if (user == null) {
			return false;
		} else {
			user.setUiPassword(password2);
			userDao.updateObject(user);
			return true;
		}
	}

	public boolean updateLimit(Userinfo user) {
		userDao.updateObject(user);
		return true;
	}

	public boolean updateStatus(String userId, int status, String createrId) {
		Userinfo user = (Userinfo) userDao.loadObject(
				com.wyzz.hr.pojo.Userinfo.class, userId, null, new boolean[0]);
		if (user == null)
			return false;
		if (createrId != null) {
			user.setUiLastChangeBy(new Employee(createrId));
			user.setUiLastChangeTime(new Date());
		}
		user.setUiStatus(Integer.valueOf(status));
		return true;
	}

	public List getObjects(Class clas) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(clas);
		return userDao.findByCriteria(detachedCriteria);
	}

	public List searchUserList(String empName, Userinfo user, String depart,
			String manager, String role, Pager page) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		if (empName != null && empName.length() > 0)
			detachedCriteria
					.add(Restrictions
							.or(
									Restrictions
											.sqlRestriction((new StringBuilder())
													.append(
															"ui_emp_no in (select emp_no from employee where emp_distinct_no like '%")
													.append(empName.trim())
													.append("%')").toString()),
									Restrictions
											.sqlRestriction((new StringBuilder())
													.append(
															"ui_emp_no in (select emp_no from employee where emp_name like '%")
													.append(empName.trim())
													.append("%')").toString())));
		if (user != null && user.getUiLevelRestrict() != null)
			detachedCriteria.add(Restrictions.eq("uiLevelRestrict", Integer
					.valueOf(user.getUiLevelRestrict().intValue())));
		if (depart != null && depart.trim().length() > 0)
			detachedCriteria
					.add(Restrictions
							.sqlRestriction(
									"(ui_emp_no in (select emp_no from employee, department where employee.emp_dept_no = department.department_no and department.department_no = ?))",
									depart, Hibernate.STRING));
		if (manager != null && manager.trim().length() > 0)
			detachedCriteria
					.add(Restrictions
							.sqlRestriction(
									"(ui_emp_no in (select emp_no from employee where emp_sup_no = ?))",
									manager, Hibernate.STRING));
		if (page == null) {
			detachedCriteria.addOrder(Order.desc("uiCurrentLoginTime"));
			return userDao.findByCriteria(detachedCriteria);
		}
		checkOrderMethod(detachedCriteria, page.getOrder());
		List result;
		if (role == null || role.length() < 1) {
			splitPage(detachedCriteria, page);
			result = userDao.findByCriteria(detachedCriteria, page
					.getPageSize(), page.getCurrentPage());
			return result;
		}
		result = userDao.findByCriteria(detachedCriteria);
		List resultList = new ArrayList();
		int resultSize = result.size();
		label0: for (int i = 0; i < resultSize; i++) {
			List array = ((Userinfo) result.get(i)).getUiRoleList();
			int size = array.size();
			int j = 0;
			do {
				if (j >= size)
					continue label0;
				if (((String) array.get(j)).trim().equals(role.trim())) {
					resultList.add((Userinfo) result.get(i));
					continue label0;
				}
				j++;
			} while (true);
		}

		listSplitPage(resultList, page);
		int readBegain = (page.getCurrentPage() - 1) * page.getPageSize();
		int readEnd = page.getCurrentPage() * page.getPageSize() >= resultList
				.size() ? resultList.size() : page.getCurrentPage()
				* page.getPageSize();
		List pagedList = new ArrayList();
		for (int i = readBegain; i < readEnd; i++)
			pagedList.add(resultList.get(i));

		return pagedList;
	}

	private void listSplitPage(List resultList, Pager page) {
		int size = resultList.size();
		SysConfigManager sysConfigManager = DatabaseSysConfigManager
				.getInstance();
		int pageSize = Integer.valueOf(
				sysConfigManager.getProperty("sys.split.pages")).intValue();
		page.init(size, pageSize);
		if (page.getOperate() != null
				&& "previous".equalsIgnoreCase(page.getOperate()))
			page.previous();
		if (page.getOperate() != null
				&& "next".equalsIgnoreCase(page.getOperate()))
			page.next();
		if (page.getOperate() != null
				&& "first".equalsIgnoreCase(page.getOperate()))
			page.first();
		if (page.getOperate() != null
				&& "last".equalsIgnoreCase(page.getOperate()))
			page.last();
	}

	private void splitPage(DetachedCriteria detachedCriteria, Pager page) {
		int size = userDao.findRowCountByCriteria(detachedCriteria);
		SysConfigManager sysConfigManager = DatabaseSysConfigManager
				.getInstance();
		int pageSize = Integer.valueOf(
				sysConfigManager.getProperty("sys.split.pages")).intValue();
		detachedCriteria.setProjection(null);
		page.init(size, pageSize);
		if (page.getOperate() != null
				&& "previous".equalsIgnoreCase(page.getOperate()))
			page.previous();
		if (page.getOperate() != null
				&& "next".equalsIgnoreCase(page.getOperate()))
			page.next();
		if (page.getOperate() != null
				&& "first".equalsIgnoreCase(page.getOperate()))
			page.first();
		if (page.getOperate() != null
				&& "last".equalsIgnoreCase(page.getOperate()))
			page.last();
	}

	public void checkOrderMethod(DetachedCriteria detachedCriteria, String order) {
		if (order != null && order.trim().length() > 1
				&& order.indexOf('-') != -1) {
			String pram[] = order.split("-");
			if (pram[0] == null || pram[0].length() < 1) {
				detachedCriteria.addOrder(Order.desc("uiCurrentLoginTime"));
				return;
			}
			String fetch[] = pram[0].split("\\.");
			String orde = pram[0];
			if (fetch.length > 1) {
				String str = "";
				String fetc = "";
				for (int len = 0; len < fetch.length - 1; len++) {
					detachedCriteria.createAlias((new StringBuilder()).append(
							fetc).append(fetch[len]).toString(),
							(new StringBuilder()).append("ord").append(len)
									.toString());
					fetc = (new StringBuilder()).append(fetc)
							.append(fetch[len]).append(".").toString();
					str = (new StringBuilder()).append("ord").append(len)
							.append(".").toString();
				}

				orde = (new StringBuilder()).append(str).append(
						pram[0].substring(pram[0].lastIndexOf(".") + 1))
						.toString();
			}
			if (pram.length == 2 && pram[1].equalsIgnoreCase("up"))
				detachedCriteria.addOrder(Order.asc(orde));
			else
				detachedCriteria.addOrder(Order.desc(orde));
		} else {
			detachedCriteria.addOrder(Order.desc("uiCurrentLoginTime"));
		}
	}

	public boolean checkAuthModule(Userinfo user, String authModule) {
		if (user == null)
			return false;
		List userAuth = user.getUiAuthList();
		if (userAuth == null)
			return false;
		DetachedCriteria detachedCriteriaA = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Authority.class);
		detachedCriteriaA.add(Restrictions.eq("authorityModuleNo", authModule));
		List resultAuth = userDao.findByCriteria(detachedCriteriaA);
		if (resultAuth == null || resultAuth.isEmpty())
			return false;
		for (Iterator i$ = resultAuth.iterator(); i$.hasNext();) {
			Authority auth = (Authority) i$.next();
			if (userAuth.contains(auth.getId().toString()))
				return true;
		}

		return false;
	}

	public boolean checkAuthModule(Userinfo user, String authModule,
			String authCondition) {
		if (user == null)
			return false;
		List userAuth = user.getUiAuthList();
		if (userAuth == null)
			return false;
		DetachedCriteria detachedCriteriaA = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Authority.class);
		detachedCriteriaA.add(Restrictions.eq(
				Authority.PROP_AUTHORITY_MODULE_NO, authModule));
		detachedCriteriaA.add(Restrictions.eq(
				Authority.PROP_AUTHORITY_CONDITION_NO, Integer.valueOf(Integer
						.parseInt(authCondition))));
		List resultAuth = userDao.findByCriteria(detachedCriteriaA);
		if (resultAuth == null || resultAuth.isEmpty())
			return false;
		return userAuth.contains(((Authority) resultAuth.get(0)).getId()
				.toString());
	}

	public int getAdminCount(String authModule) {
		int count = 0;
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		List result = userDao.findByCriteria(detachedCriteria);
		DetachedCriteria detachedCriteriaA = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Authority.class);
		detachedCriteriaA.add(Restrictions.eq("authorityModuleNo", authModule));
		List resultAuth = userDao.findByCriteria(detachedCriteriaA);
		if (resultAuth == null || resultAuth.isEmpty())
			return 10;
		int resultAuthSize = resultAuth.size();
		int resultSize = result.size();
		label0: for (int i = 0; i < resultSize; i++) {
			List auths = ((Userinfo) result.get(i)).getUiAuthList();
			int j = 0;
			do {
				if (j >= resultAuthSize)
					continue label0;
				String authId = ((Authority) resultAuth.get(0)).getId()
						.toString();
				if (auths.contains(authId)) {
					count++;
					continue label0;
				}
				j++;
			} while (true);
		}

		return count;
	}

	public String getAuthoritysByRole(String roles) {
		String[] roleNo = roles.split(",");
		if (roleNo == null)
			return null;
		List roleNoList = new ArrayList();
		for (int i = 0; i < roleNo.length; ++i) {
			roleNoList.add(Integer.valueOf(Integer.parseInt(roleNo[i])));
		}
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Role.class);
		detachedCriteria.add(Restrictions.in("roleNo", roleNoList));
		List roleList = this.userDao.findByCriteria(detachedCriteria);
		System.out.println(roleList.get(0)+"ttttttt");
		if ((roleList == null) || (roleList.size() == 0))
			return null;
		Iterator iter = roleList.iterator();
		Set authSet = new HashSet();
		while (iter.hasNext()) {
			String[] auths = ((Role) iter.next()).getRoleAuthority().split(",");
			for (int i = 0; i < auths.length; ++i) {
				authSet.add(auths[i]);
			}
		}
		if (authSet.size() == 0)
			return null;
		String authString = "";
		Iterator authItor = authSet.iterator();
		while (authItor.hasNext()) {
			authString = authString + authItor.next() + ",";
		}
		if (authString.length() == 0)
			return null;
		authString = authString.substring(0, authString.length() - 1);
		return authString;
	}

	public void save(Userinfo userinfo) {
		userDao.saveObject(userinfo);
	}

	public boolean updatePasswordBy(String userId, String userName,
			String password, String creatBy) {
		Userinfo user = (Userinfo) userDao.loadObject(
				com.wyzz.hr.pojo.Userinfo.class, userId, null, new boolean[0]);
		if (user == null)
			return false;
		if (userName != null)
			user.setUiUsername(userName);
		user.setUiPasswordEncrypt(StringUtil.encodePassword(password));
		if (creatBy != null) {
			user.setUiLastChangeBy(new Employee(creatBy));
			user.setUiLastChangeTime(new Date());
		}
		userDao.updateObject(user);
		return true;
	}

	public boolean isRoleNoHasAuth(Integer roleNo[], String moduleId) {
		List roleNoList = new ArrayList();
		for (int i = 0; i < roleNo.length; i++)
			roleNoList.add(roleNo[i]);

		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Role.class);
		detachedCriteria.add(Restrictions.in("roleNo", roleNoList));
		List roleList = userDao.findByCriteria(detachedCriteria);
		if (roleList == null || roleList.size() == 0)
			return false;
		Iterator iter = roleList.iterator();
		Set authSet = new HashSet();
		while (iter.hasNext()) {
			String auths[] = ((Role) iter.next()).getRoleAuthority().split(",");
			int i = 0;
			while (i < auths.length) {
				authSet.add(Integer.valueOf(Integer.parseInt(auths[i])));
				i++;
			}
		}
		if (authSet.size() == 0)
			return false;
		List list = new ArrayList();
		list.addAll(authSet);
		DetachedCriteria detachedCriteria2 = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Authority.class);
		detachedCriteria2.add(Restrictions.in("id", list));
		List authList = userDao.findByCriteria(detachedCriteria2);
		if (authList == null || authList.size() == 0)
			return false;
		for (Iterator authIter = authList.iterator(); authIter.hasNext();) {
			String authString = ((Authority) authIter.next())
					.getAuthorityModuleNo();
			if (moduleId.equals(authString))
				return true;
		}

		return false;
	}

	public boolean ipIsValid(String rangeIP, String loginIP) {
		boolean isvalid = false;
		if (rangeIP == null)
			return true;
		if (rangeIP.indexOf("-") == -1 && rangeIP.indexOf("*") == -1) {
			if (loginIP.equals(rangeIP))
				isvalid = true;
		} else if (rangeIP.indexOf("-") == -1
				&& rangeIP.indexOf("*") == rangeIP.length() - 1) {
			String rangeIPs[] = replacePoint(rangeIP).split("-");
			String loginIPs[] = replacePoint(loginIP).split("-");
			int i = 0;
			do {
				if (i >= 3)
					break;
				if (!loginIPs[i].equals(rangeIPs[i])) {
					isvalid = false;
					break;
				}
				isvalid = true;
				i++;
			} while (true);
		} else if (rangeIP.indexOf("-") != -1) {
			String rangeIPmin[] = replacePoint(rangeIP.split("-")[0])
					.split("-");
			String rangeIPmax[] = replacePoint(rangeIP.split("-")[1])
					.split("-");
			String logip[] = replacePoint(loginIP).split("-");
			String rangeIP1 = "";
			String rangeIP2 = "";
			loginIP = "";
			for (int i = 0; i < 4; i++) {
				if (rangeIPmin[i].length() == 1)
					rangeIPmin[i] = (new StringBuilder()).append("00").append(
							rangeIPmin[i]).toString();
				else if (rangeIPmin[i].length() == 2)
					rangeIPmin[i] = (new StringBuilder()).append("0").append(
							rangeIPmin[i]).toString();
				rangeIP1 = (new StringBuilder()).append(rangeIP1).append(
						rangeIPmin[i]).toString();
				if (rangeIPmax[i].length() == 1)
					rangeIPmax[i] = (new StringBuilder()).append("00").append(
							rangeIPmax[i]).toString();
				else if (rangeIPmax[i].length() == 2)
					rangeIPmax[i] = (new StringBuilder()).append("0").append(
							rangeIPmax[i]).toString();
				rangeIP2 = (new StringBuilder()).append(rangeIP2).append(
						rangeIPmax[i]).toString();
				if (logip[i].length() == 1)
					logip[i] = (new StringBuilder()).append("00").append(
							logip[i]).toString();
				else if (logip[i].length() == 2)
					logip[i] = (new StringBuilder()).append("0").append(
							logip[i]).toString();
				loginIP = (new StringBuilder()).append(loginIP)
						.append(logip[i]).toString();
			}

			if (loginIP.compareTo(rangeIP1) > 0
					&& loginIP.compareTo(rangeIP2) < 0)
				isvalid = true;
		}
		return isvalid;
	}

	public boolean macIsValid(String macRestrict, String loginMac) {
		return macRestrict.equals(loginMac);
	}

	private String replacePoint(String s) {
		String result = "";
		char ss[] = s.toCharArray();
		for (int i = 0; i < ss.length; i++) {
			if (ss[i] == '.')
				ss[i] = '-';
			result = (new StringBuilder()).append(result).append(ss[i])
					.toString();
		}

		return result;
	}

	public String updateSignFree(String userId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Userinfo.class);
		detachedCriteria
				.add(Restrictions.eq(Userinfo.PROP_UI_USERNAME, userId));
		List list = userDao.findByCriteria(detachedCriteria);
		if (list == null || list.isEmpty())
			return "noUser";
		Userinfo userinfo = (Userinfo) list.get(0);
		if (userinfo.getUiStatus().intValue() == 0)
			return "hasStoped";
		detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.add(Restrictions.eq(Employee.PROP_EMP_DISTINCT_NO,
				userId));
		list = userDao.findByCriteria(detachedCriteria);
		Employee employee = (Employee) list.get(0);
		if (employee.getEmpStatus().intValue() == 0)
			return "hasLeave";
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request == null)
			request = WebContextFactory.get().getHttpServletRequest();
		String loginIp = request.getRemoteAddr();
		if ("127.0.0.1".equals(loginIp))
			try {
				String tempIp = InetAddress.getLocalHost().toString();
				loginIp = tempIp.substring(tempIp.lastIndexOf("/") + 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		Integer level = userinfo.getUiLevelRestrict();
		if (level.intValue() == 1
				&& !ipIsValid(userinfo.getUiIpRestrict(), loginIp))
			return "ipError";
		userinfo.setUiLastLoginIp(loginIp);
		Date date = userinfo.getUiCurrentLoginTime();
		if (date != null)
			userinfo.setUiLastLoginTime(date);
		else
			userinfo.setUiLastLoginTime(new Date());
		userinfo.setUiCurrentLoginTime(new Date());
		userinfo.setUiLastLoginIp(userinfo.getUiLastLoginIp());
		userDao.updateObject(userinfo);
		return "success";
	}

	private UserDao userDao;
}
